package com.jh.track.mill.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jh.track.mill.pojo.entity.TrackRhf;

import com.jh.track.mill.mapper.TrackRhfMapper;
import com.jh.track.mill.service.ITrackRhfService;
import com.jh.track.mill.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ：xy
 * @date ：Created in 2021/4/20 22:24
 * @description：
 * @version: v 1.0.0
 * @email: xy100826@163.com
 */
@Service
public class TrackRhfServiceImpl extends ServiceImpl<TrackRhfMapper, TrackRhf>  implements ITrackRhfService , ApplicationEventPublisherAware {

    @Autowired
    private WebSocketServer webSocketServer;

  private ApplicationEventPublisher applicationEventPublisher;
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    /**
     *查询加热炉内的物料
     * @author xy
     * @date 2021/4/21 11:00
     * @return java.util.List<com.jh.track.mill.pojo.entity.TrackRhf>
     */
    @Override
    public List<TrackRhf> findALlTrackRhf() {
        List<TrackRhf> trackRhfs = this.baseMapper.selectList(null);
        return trackRhfs;
    }

    /**
     *入炉
     * @author xy
     * @date 2021/4/21 10:58
     */
    @Override
    public void insertTrackRhf(TrackRhf trackRhf) {
        int insert = this.baseMapper.insert(trackRhf);
        this.sendAllWebSocket(insert);

    }

    /**
     *更新
     * @author xy
     * @date 2021/4/21 11:02
     */
    @Override
    public void updateTrackRhf(TrackRhf trackRhf) {
        int update = this.baseMapper.update(trackRhf, null);
        this.sendAllWebSocket(update);
    }

    /**
     *出炉
     * @author xy
     * @date 2021/4/21 11:02
     */
    @Override
    public void deleteTrackRhf(TrackRhf trackRhf) {
        int deleteById = this.baseMapper.deleteById(trackRhf.getId());
        this.sendAllWebSocket(deleteById);
    }

    @Override
    public TrackRhf findById(Long id) {
        TrackRhf trackRhf = this.baseMapper.selectById(id);
        if (trackRhf != null){
            sendAllWebSocket(1);
        }
        return trackRhf;
    }

    public void  sendAllWebSocket(int flag){
            if (flag > 0) {
                List<TrackRhf> trackRhfs = this.findALlTrackRhf();
                String rhfs = JSON.toJSONString(trackRhfs);
                webSocketServer.broadcast(rhfs);
            }
    }
}
